<?

class generate_project_task extends system_task
{
	protected $type = 2;

	public function execute( array $params = array() )
	{
		$this->name = basename(getcwd());
		$this->path = getcwd();
		$this->fpath = realpath(dirname(__FILE__) . '/../../../');
		
		$this->out('Generating new project ' . $this->name);

		$this->out('Generating files and folders...');

		$template_folder = realpath(dirname(__FILE__) . '/../../../assets/generate/project');
		$this->copy_dir($template_folder, $this->path);
		define('PROJECT_PATH', $this->path);
		
		$this->setup_nginx();
		$this->setup_modes();
		$this->setup_versioning();
	}

	protected function copy_dir( $src, $dst )
	{
		$d = opendir($src);
		while ( $f = readdir($d) )
		{
			if ( in_array($f, array('.', '..', '.svn')) ) continue;

			$path = $src . '/' . $f;
			$this->out('-' . $f);

			if ( is_dir($path) )
			{
				mkdir($dst . '/' . $f);
				$this->copy_dir($path, $dst . '/' . $f);
			}
			else
			{
				$content = file_get_contents($path);
				$content = str_replace(
					array('{$name}', '{$path}', '{$fpath}'),
					array($this->name, $this->path, $this->fpath),
					$content
				);

				file_put_contents($dst . '/' . $f, $content);
			}
		}
	}
	
	public function setup_nginx()
	{
		$this->out('Setting up nginx configuration...');
		
		$task = new compile_nginx_task();
		$task->execute();
		
		$possible_dirs = array(
			'/etc/nginx/sites-enabled',
			'/usr/local/nginx/conf/sites-enabled',
			'/etc/nginx/vhosts',
			'/usr/local/nginx/conf/vhosts',

		);
		
		foreach ( $possible_dirs as $dir )
		{
			if ( !is_dir($dir) ) continue;
			
			$this->out('  in ' . $dir);
			
			exec('sudo ln -s ' . $this->path . '/config/nginx/dev.conf ' . $dir . '/' . $this->name . '.conf');
			exec('sudo nginx -s reload');
		}
	}
	
	public function setup_versioning()
	{
		if ( is_dir($this->path . '/.svn') )
		{
			$this->out('SVN processing...');
			
			exec('svn add *');
			exec('svn propset svn:ignore \'*\' data/cache');
			exec('svn propset svn:ignore \'nbproject\' .');
			exec('svn commit -m "initial autocommit by phlight"');
			$this->out('SVN commit finished');
		}
	}
	
	public function setup_modes()
	{
		$this->out('Setting modes...');
		
		chmod($this->path . '/data/cache', 0777);
		chmod($this->path . '/run', 0777);
		chmod($this->path . '/apps/main/web/public', 0777);
	}
}